package com.zxy.paycenter.modules;

import com.alibaba.fastjson.JSONObject;
import com.zxy.paycenter.common.constants.ResponseCodeConstant;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 控制器基类
 *
 * @author zxy
 */
@Slf4j
public class BaseController {

    /**
     * 获得请求request的所有参数
     *
     * @param request 请求
     * @return 参数Map
     */
    protected Map<String, String> getParamsMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>(10);
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // TODO 乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }
        log.info("params={}", params);
        return params;
    }

    /**
     * 组装响应信息
     *
     * @param code    响应码
     * @param message 响应信息
     * @param key     响应信息Key
     * @param value   响应信息值
     * @return 响应信息
     */
    protected JSONObject packProducterSuccessResponse(String code, String message, String[] key, Object[] value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("message", message);
        for (int i = 0; i < key.length; i++) {
            jsonObject.put(key[i], value[i]);
        }
        return jsonObject;
    }

    /**
     * 组装响应信息
     *
     * @param key   响应信息Key
     * @param value 响应信息值
     * @return 响应信息
     */
    protected JSONObject packProducterSuccessResponse(String[] key, Object[] value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", ResponseCodeConstant.SUCCESS);
        jsonObject.put("message", "成功");
        for (int i = 0; i < key.length; i++) {
            jsonObject.put(key[i], value[i]);
        }
        return jsonObject;
    }
}
